﻿using SuporeSliplampApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
//using PdfSharp;
//using PdfSharp.Drawing;
//using PdfSharp.Pdf;
using System.IO;
using System.Windows.Markup;
using System.Xml.Linq;
using Microsoft.Win32;
//using iTextSharp.text;
//using iTextSharp.text.pdf;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Pdf.Advanced;
using SuporeSliplampApp.ViewModels;
using System.Drawing;
using SuporeSliplampApp.Util;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// PrintView.xaml 的交互逻辑
    /// </summary>
    public partial class PrintView : Window
    {
        PrintModel model;
        public PrintView( PrintModel printModel)
        {

            model = printModel;          
            InitializeComponent();
            initData();
        }

        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            if (printDialog.ShowDialog() == true)
            {
                printDialog.PrintVisual(printArea,"r");

            }
        }
        private void initData()
        {
            PatientModel model1 = new PatientModel();
            //model1 = model.Patient;
            //txtName.Text = model1.Name;
            txtName.Text = model.Patient.Name;
            txtSex.Text = model.Patient.SEX;
            //txtName.Text = cameraView.NameTxt;
            //int date = DateTime.Now.Year;
            ////int date2 =Convert.ToInt32( model.Patient.Str_Birth.Substring(0, 4));
            //int date2 = model.Patient.Birth.Year;
            //if (date2.ToString().Length <4)
            //{
            //    txtAge.Text ="";
            //}
            //else
            //{
            //    txtAge.Text = Convert.ToString(date -date2);
            //}

            string birthDateString = model.Patient.Str_Birth;
            int age = CalculateAgeFromBirthDate(birthDateString);
            txtAge.Text = Convert.ToString(age);

            txtNo.Text =model.Patient.P_ID;
            txtType.Text = model.ExamType;
            result.Text = model.ExamResult;
            if(Common.DateIndex == 0)
            {
                printDate.Text = DateTime.Now.ToString("yyyy/MM/dd");
            }
            else if (Common.DateIndex == 1)
            {
                printDate.Text = DateTime.Now.ToString("MM/yyyy/dd");
            }
            else if (Common.DateIndex == 2)
            {
                printDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            }

        }

        public static int CalculateAgeFromBirthDate(string birthDateString, string dateFormat = "yyyy-MM-dd")
        {
            if (DateTime.TryParseExact(birthDateString, dateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime birthDate))
            {
                int age = DateTime.Today.Year - birthDate.Year;
                if (birthDate > DateTime.Today.AddYears(-age)) age--;
                return age;
            }
            else
            {
                // 如果解析失败，返回一个错误指示，例如 -1，或抛出一个异常
                throw new ArgumentException("Invalid birth date string format.");
            }
        }


        //private void pdfPrint_Click(object sender, RoutedEventArgs e)
        //{
        //    string pdfFilePath = null;
        //    try
        //    {
        //        //PdfDocument document = new PdfDocument();
        //        /*PdfPage page = document.AddPage();
        //        double width = printArea.ActualWidth;
        //        double height = printArea.ActualHeight;

        //        string xamlString = XamlWriter.Save(printArea);
        //        string x = "<Grid Name=\"printArea\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">\r\n<Grid.RowDefinitions><RowDefinition Height=\"140\" /><RowDefinition Height=\"*\" />\r\n<RowDefinition Height=\"160\" /></Grid.RowDefinitions><StackPanel><StackPanel HorizontalAlignment=\"Center\">\r\n<TextBlock Text=\"\" FontFamily=\"\" FontSize=\"40\" Foreground=\"#FF414141\" Margin=\"0,20,0,5\" />\r\n</StackPanel><StackPanel Orientation=\"Horizontal\" Margin=\"50,20,50,20\"><TextBlock Text=\":\" FontSize=\"18\" />\r\n<TextBlock Text=\"tt\" FontSize=\"18\" Name=\"txtName\" Margin=\"10,0,0,0\" /><TextBlock Text=\":\" FontSize=\"18\" Margin=\"80,0,0,0\" />\r\n<TextBlock Text=\"mingzi\" FontSize=\"18\" Name=\"txtSex\" Margin=\"10,0,0,0\" /><TextBlock Text=\":\" FontSize=\"18\" Margin=\"80,0,0,0\" />\r\n<TextBlock FontSize=\"18\" Name=\"txtAge\" Margin=\"10,0,0,0\" /><TextBlock Text=\":\" FontSize=\"18\" Margin=\"80,0,0,0\" />\r\n<TextBlock FontSize=\"18\" Name=\"txtNo\" Margin=\"10,0,0,0\" /><TextBlock Text=\":\" FontSize=\"18\" Margin=\"150,0,0,0\" />\r\n<TextBlock FontSize=\"18\" Name=\"txtType\" Margin=\"10,0,0,0\" /></StackPanel><StackPanel Background=\"#FF414141\" Height=\"1\" Margin=\"10,0,10,0\" />\r\n</StackPanel><StackPanel Margin=\"10,10,10,10\" Grid.Row=\"1\"><Image Stretch=\"Uniform\" Name=\"img\" /></StackPanel><StackPanel Margin=\"10,10,10,10\" Grid.Row=\"2\">\r\n<StackPanel Margin=\"50,0,50,0\"><TextBlock Text=\"：\" FontSize=\"18\" /><TextBlock FontSize=\"18\" Name=\"result\" Margin=\"10,0,0,0\" />\r\n</StackPanel><StackPanel Background=\"#FF414141\" Height=\"1\" Margin=\"10,0,10,0\" /><StackPanel HorizontalAlignment=\"Right\">\r\n<StackPanel Orientation=\"Horizontal\" Margin=\"0,10,30,5\"><TextBlock Text=\"\" /><TextBlock Text=\"2024/04/30\" Name=\"checkDate\" />\r\n</StackPanel><StackPanel Orientation=\"Horizontal\" Margin=\"0,0,30,5\"><TextBlock Text=\"\" /><TextBlock Text=\"2024/05/07\" Name=\"printDate\" />\r\n</StackPanel>\r\n<StackPanel Orientation=\"Horizontal\" Margin=\"0,0,30,5\"><TextBlock Text=\"\" />\r\n<TextBlock Text=\"admin\" Name=\"checkPerson\" />\r\n</StackPanel></StackPanel>\r\n</StackPanel>\r\n</Grid>";

        //        StreamReader streamReader = new StreamReader(x);
        //        System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(streamReader);
        //        UIElement element = (UIElement)XamlReader.Load(xmlReader);

        //        RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)width, (int)height, 96d, 96d, PixelFormats.Pbgra32);
        //        renderBitmap.Render(element);

        //        // 创建 XImage 对象
        //        XImage image = XImage.FromBitmapSource(renderBitmap);

        //        double pageWidth = page.Width.Point;
        //        double pageHeight = page.Height.Point;

        //        double scaleX = pageWidth / width;
        //        double scaleY = pageHeight / height;
        //        double scale = Math.Min(scaleX, scaleY);

        //        // 计算居中偏移量
        //        double offsetX = (pageWidth - scale * width) / 2d;
        //        double offsetY = (pageHeight - scale * height) / 2d;

        //        XGraphics gfx = XGraphics.FromPdfPage(page);
        //        gfx.ScaleTransform(scale);
        //        gfx.TranslateTransform(offsetX / scale, offsetY / scale);
        //        // 将 XImage 对象绘制到 PdfPage 上
        //        gfx.DrawImage(image, 0, 0);
        //        SaveFileDialog dlg = new SaveFileDialog();
        //        dlg.FileName ="Document";
        //        dlg.DefaultExt =".pdf";
        //        dlg.Filter ="PDF文件(*.pdf)|*.pdf";
        //        Nullable<bool>result = dlg.ShowDialog();
        //        if (result == true)
        //        {
        //            pdfFilePath = dlg.FileName;
        //            document.Save(pdfFilePath);
        //        }*/
        //        // 保存 PdfDocument 到文件或输出流中
        //        /*Document document = new Document(PageSize.A4);
        //        PdfWriter writer = PdfWriter.GetInstance(document,new FileStream(pdfFilePath,FileMode.Create));
        //        document.Open();
        //        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)printArea.ActualWidth,(int)printArea.ActualHeight,96,96,
        //            PixelFormats.Pbgra32);
        //        renderTargetBitmap.Render(printArea);
        //        System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(renderTargetBitmap.GetValue()));*/
        //    }
        //    catch (Exception ex)
        //    {

        //        throw ex;
        //    }
        //}



        private void pdfPrint_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "PDF file (*.pdf)|*.pdf"; // 设置文件类型过滤
            saveFileDialog.DefaultExt = "pdf"; // 默认扩展名
            saveFileDialog.AddExtension = true; // 自动添加扩展名

            if (saveFileDialog.ShowDialog() == true) // 显示保存文件对话框
            {
                var printArea = this.FindName("printArea") as Grid;
                if (printArea != null)
                {
                    var bitmap = CaptureControl(printArea);
                    SaveBitmapToPdf(bitmap, saveFileDialog.FileName); // 传递用户选定的文件名到保存函数
                }
            }
        }



        private void SaveBitmapToPdf(BitmapSource bitmap , string filePath)
        {
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            MemoryStream stream = new MemoryStream();
            encoder.Save(stream);
            stream.Position = 0;

            PdfDocument document = new PdfDocument();
            PdfPage page = document.AddPage();

            page.Width = bitmap.Width;
            page.Height = bitmap.Height;

            XGraphics gfx = XGraphics.FromPdfPage(page);
            XImage img = XImage.FromStream(stream);

            gfx.DrawImage(img, 0, 0 , page.Width, page.Height);
            document.Save(filePath);
            document.Close();
            stream.Close();
        }



        private BitmapSource CaptureControl(FrameworkElement element)
        {
            double dpi = 96d;
            RenderTargetBitmap bitmap = new RenderTargetBitmap(
                (int)element.ActualWidth,
                (int)element.ActualHeight,
                dpi,
                dpi,
                PixelFormats.Pbgra32);

            element.Measure(new System.Windows.Size((int)element.ActualWidth, (int)element.ActualHeight));
            element.Arrange(new Rect(new System.Windows.Size((int)element.ActualWidth, (int)element.ActualHeight)));

            bitmap.Render(element);
            return bitmap;
        }






        //public void ConvertToPdf(UIElement element,string filename)
        //{
        //    PdfDocument document = new PdfDocument();
        //    PdfPage page = document.AddPage();
        //    XGraphics gfx = XGraphics.FromPdfPage(page);

        //    double dpiY = 96;
        //    double scale = dpiY/96.0;
        //    Size size = new Size(element.RenderSize.Width,element.RenderSize.Height);
        //    Visual visual = element;
        //    RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)(size.Width * scale),
        //        (int)(size.Height *scale),
        //        96,
        //        96,
        //        PixelFormats.Pbgra32);

        //    VisualBrush visualBrush = new VisualBrush(visual);
        //    DrawingVisual drawingVisual = new DrawingVisual();
        //    DrawingContext drawingContext = drawingVisual.RenderOpen();
        //    drawingContext.PushTransform(new ScaleTransform(scale,scale));
        //    drawingContext.DrawRectangle(visualBrush,null,new Rect(new Point(0,0),size));
        //    drawingContext.Pop();
        //    drawingContext.Close();

        //    renderTarget.Render(drawingVisual);
        //    BitmapSource bitmap = renderTarget;
        //    MemoryStream stream = new MemoryStream();

        //    //PdfImage image = new PdfImage(document,bitmap);
        //    //XRect rect = new XRect(0,0,image);

        //}

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
